package com.luohoufa.ms.order.controller;

import com.luohoufa.ms.order.model.ProductInfo;
import com.luohoufa.ms.product.client.ProductClient;
import com.luohoufa.ms.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
public class ClientController {

//    @Autowired
//    private LoadBalancerClient loadBalancerClient;

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private ProductClient productClient;


    @GetMapping("/getProductMsg")
    public String getProductMsg() {
        // 1. 第一种方式, 直接用RestTemplate
        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject("http://localhost:8772/msg", String.class);

        // 2. 第二种方式, 用LoadBalancerClient通过服务名获取url，再用RestTemplate
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
//        String host = serviceInstance.getHost();
//        int port = serviceInstance.getPort();
//        String url = String.format("http://%s:%s", host, port) + "/msg";
//        RestTemplate restTemplate = new RestTemplate();
//        String response = restTemplate.getForObject(url, String.class);

        // 3. 第三种方式，用LoadBalanced注解实现
//        String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);

        String response = productClient.productMsg();

        log.info("response={}", response);
        return response;
    }

    @GetMapping("/getProductList")
    public String getProductList() {
        List<ProductInfoOutput> list = productClient.listForOrder(Arrays.asList("157875227953464068", "164103465734242707"));
        log.info("response={}", list);
        return "ok";
    }

}
